import random
from loguru import logger
from django.shortcuts import render
from django.conf import settings
from apps.actors import models
from django.core.paginator import Paginator, EmptyPage


def actor_list(request):
    actor_queryset = models.Actor.objects.filter(

    ).exclude(avatar='actors/portrait/default.png').order_by('-score').all()
    logger.debug('查询演员数据>>>{}', actor_queryset)
    paginator = Paginator(actor_queryset, 12)
    page = request.GET.get('page', 1)
    try:
        actors = paginator.page(page)
    except EmptyPage:
        actors = paginator.page(paginator.num_pages)

    # 返回测试数据
    # actor_avatar_test_data(actors)
    return render(request, 'actors/actors_list.html', {'actors': actors})


def actor_detail_info(requests, pk):
    actor = models.Actor.objects.filter(pk=pk, avatar__isnull=False).first()
    # logger.debug('获取di-{}演员详情', actor.details_actor.roma)

    related_actors = models.Actor.objects.filter(avatar__isnull=False).order_by('-score').all()[:10]
    # 查询电影
    work_films = models.Actor.objects.prefetch_related(
        'film_roles__film',
        "film_roles__film__film_to_poster"
    ).get(pk=pk)
    work_films_list = []
    for films in work_films.film_roles.order_by('-film__critic_rating', '-film__year').all()[:6]:
        poster = films.film.film_to_poster.filter(type=2).first()
        if poster and poster.poster.name:
            poster_url = poster.poster.url
        else:
            poster_url = settings.DEFAULT_PICTURE_URL
        work_films_list.append(
            {
                'id': films.film_id,
                'title': films.film.num,
                'num': films.film.title,
                'rating': films.film.rating,
                'year': films.film.year,
                'poster': poster_url

            }
        )

    return render(
        requests,
        'actors/actors_detail.html',
        {
            'actor': actor,
            'related_actors': related_actors,
            'work_films_list': work_films_list
        }
    )
